package com.yl.applicationsecurity.config;

import com.yl.applicationsecurity.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 鹤仙问鹿仙
 * @program: Application-security
 * @description:
 * @date 2025-01-14 16:12:26
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 优先处理空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {NullPointerException.class})
    @ResponseBody
    public Object nullPointerExceptionHandler(HttpServletRequest request, NullPointerException e){
        LOGGER.error("发生空指针异常，请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        e.printStackTrace();
        return  Result.error("发生空指针异常");
    }


    @ExceptionHandler(value = {ServletException.class})
    @ResponseBody
    public Object servletExceptionHandler(HttpServletRequest request, Exception e){
        LOGGER.error("未知异常，请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        e.printStackTrace();
        return  Result.error(e.getMessage());
    }
    /**
     * 兜底处理其它异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, Exception e){
        LOGGER.error("未知异常，请求地址：{}, 错误信息：{}", request.getRequestURI(), e.getMessage());
        e.printStackTrace();
        return  Result.error(e.getMessage());
    }
}
